/**
 * @Project: InteractAPI
 * @Title: SocetFactory.java
 * @Package com.j99view.interact.utils
 * @Description: TODO
 * Copyright: Copyright (c) 2010 
 * Company:ENDER.crop
 * 
 * @author ender
 * @date 2013-8-18 下午9:43:41
 * @version V1.0.0
 */
package com.j99view.interact.utils;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Set;

import com.j99view.interact.Player;

/**
 * @ClassName: SocetFactory
 * @Description: TODO
 * @author ender
 * @date 2013-8-18 下午9:43:41
 *
 */
public class SocketFactory {
	/**
	 * LRU缓存机制，保存最近使用的object
	 */
	private static LRUCache<String,Socket> socketPool=null;
	
	private static int SOCKET_POOL_SIZE = 3;
	
	private SocketFactory(){
		
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Socket getSocket(Player player) throws UnknownHostException, IOException{
		if(socketPool ==  null){
			socketPool = new LRUCache(SOCKET_POOL_SIZE);
		}
		
		if(socketPool.containsKey(player.getIp())){
			return socketPool.get(player.getIp());
		}
		
		Socket socket = new Socket(player.getIp(), player.getPort());
		
		socketPool.put(player.getIp(), socket);
		
		return socket;
	}
	
	public static void main(String args[]) throws Exception{
		Player player1=new Player();
		player1.setIp("127.0.0.1");
		player1.setPort(5527);
		
		Player player2=new Player();
		player2.setIp("127.0.0.2");
		player2.setPort(5527);
		
		Player player3=new Player();
		player3.setIp("127.0.0.3");
		player3.setPort(5527);
		
		Player player4=new Player();
		player4.setIp("127.0.0.4");
		player4.setPort(5527);
		
		try {
			SocketFactory.getSocket(player1);
			SocketFactory.echoCache();
			SocketFactory.getSocket(player2);
			SocketFactory.echoCache();
			SocketFactory.getSocket(player3);
			SocketFactory.echoCache();
			SocketFactory.getSocket(player4);
			SocketFactory.echoCache();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	protected static void echoCache(){
		Set<String> set = socketPool.keySet();
		
		for(String str:set){
			System.out.println(str);
		}
		
		System.out.println("*****************************");
	}
}
